package com.CMS.client.datasource;

import java.util.ArrayList;
import java.util.List;

import com.CMS.client.RolService;
import com.CMS.client.RolServiceAsync;
import com.CMS.server.domain.Privilege;
import com.CMS.server.domain.Rol;
import com.google.gwt.core.client.GWT;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.smartgwt.client.data.DSRequest;
import com.smartgwt.client.data.DSResponse;
import com.smartgwt.client.data.DataSourceField;
import com.smartgwt.client.data.Record;
import com.smartgwt.client.rpc.RPCResponse;
import com.smartgwt.client.types.DSOperationType;
import com.smartgwt.client.types.FieldType;
import com.smartgwt.client.widgets.form.fields.SelectItem;
import com.smartgwt.client.widgets.grid.ListGridRecord;

public class RolDataSource extends BaseDataSource{

	private SelectItem privilegios = new SelectItem();
	private DataSourceField field = null;

	public RolDataSource(){
						
		field = new DataSourceField("privilegios",FieldType.ANY,"Privilegios",128,false);
		privilegios.setOptionDataSource(new PrivilegeDataSource());
		//ListGridField type = new ListGridField("type","Tipo");
		//ListGridField path = new ListGridField("path","Vista");
		//path.setDisplayField(PrivilegeDataSource.getPath());
		//type.setDisplayField(PrivilegeDataSource.getType());
		privilegios.setMultiple(true);
		privilegios.setAccessKey(getId());
		privilegios.setValueField(getId());
		privilegios.setDisplayField(getDescription());
		//privilegios.setPickListFields(type,path);
		field.setEditorType(privilegios);        
        addField(field);
	}
	
	@Override
	protected void executeFetch(final String requestId, DSRequest request,
			final DSResponse response) {
		if (request.getOperationType() == DSOperationType.FETCH){
			final int startIndex = (request.getStartRow() < 0) ? 0 : request.getStartRow();
			final int endIndex = (request.getEndRow ()== null)? -1 : request.getEndRow();
			RolServiceAsync rpc = GWT.create(RolService.class);
			try {
				rpc.getRoles(new AsyncCallback<List<Rol>>() {
					
					@Override
					public void onSuccess(List<Rol> result) {
						int size = result.size ();
		                if (endIndex >= 0) {
		                	if (endIndex < startIndex) {
		                		size = 0;
		                    }
		                    else {
		                        size = endIndex - startIndex + 1;
		                    }
		                }
		                //Creamos los registros a devolver
						Record[] regs = new Record[result.size()];
						if (size > 0) {
							for (int i = 0; i < regs.length; i++) {
								Record record = new Record();
								copyValues(result.get(i), record);
								regs[i] = record;
							}
						}
						response.setData(regs);
						//IMPORTANTE: para que funcione el paginado debemos especificar
						//el total de registro del result set
						response.setTotalRows (result.size ());
						processResponse(requestId, response);
					}
					
					@Override
					public void onFailure(Throwable caught) {
						response.setStatus(RPCResponse.STATUS_FAILURE);
						processResponse(requestId, response);
					}
				});
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}

	@Override
	protected void executeAdd(final String requestId, DSRequest request,
			final DSResponse response) {
			
		RolServiceAsync rpc = GWT.create(RolService.class);
		List<Long> lista = new ArrayList<Long>();	
		final ListGridRecord rec = new ListGridRecord (request.getData());
		//Esto es porque me devuelve un objeto medio raro, entonces lo parseo y listo
		char[] charValues = privilegios.getValue().toString().toCharArray(); 
		for(int i=0; i<charValues.length; i++){
			if(charValues[i] != ',' && charValues[i] != ' ')
				lista.add(new Long(Character.toString(charValues[i])));
		}
		rpc.createRol(rec.getAttribute(getDescription()), lista, new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub
				
			}
		});
	}

	@Override
	protected void executeUpdate(final String requestId, DSRequest request,
			final DSResponse response) {
		
		RolServiceAsync rpc = GWT.create(RolService.class);
		Record old = request.getOldValues();
		final ListGridRecord rec = new ListGridRecord (request.getData());
		List<Long> lista = new ArrayList<Long>();
		//Esto es porque me devuelve un objeto medio raro, entonces lo parseo y listo
		char[] charValues = privilegios.getValue().toString().toCharArray(); 
		for(int i=0; i<charValues.length; i++){
			if(charValues[i] != ',' && charValues[i] != ' ')
				lista.add(new Long(Character.toString(charValues[i])));
		}
		
		rpc.updatePrivileges((rec.getAttributeAsLong(getId()) == null) ? old.getAttributeAsLong(getId()) : rec.getAttributeAsLong(getId()), 
							 lista, new AsyncCallback<Void>() {

								@Override
								public void onFailure(Throwable caught) {
									response.setStatus(RPCResponse.STATUS_FAILURE);
									processResponse(requestId, response);
								}

								@Override
								public void onSuccess(Void result) {
									// TODO Auto-generated method stub
									
								}
							});
	}

	@Override
	protected void executeRemove(final String requestId, DSRequest request,
			final DSResponse response) {
		
		RolServiceAsync rpc = GWT.create(RolService.class);
		final ListGridRecord rec = new ListGridRecord (request.getData());
		rpc.deleteRol(rec.getAttributeAsLong(getId()), new AsyncCallback<Void>() {

			@Override
			public void onFailure(Throwable caught) {
				response.setStatus(RPCResponse.STATUS_FAILURE);
				processResponse(requestId, response);
			}

			@Override
			public void onSuccess(Void result) {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	private void copyValues(Rol from, Record to) {
		to.setAttribute(getDescription(), from.getDescription());
		to.setAttribute(getId(), from.getId());
		to.setAttribute(getAddDate(), from.getAddDate());
		to.setAttribute(getModDate(), from.getModDate());
		to.setAttribute(getFlagDelete(), from.getFlagDelete());
		
		List<Privilege> p = from.getPrivileges();
		String[] a = new String[p.size()];
		for(int i=0; i<p.size(); i++){				
			a[i] = Long.toString(p.get(i).getId());
		}
		privilegios.setValues(a);
	}

}
